<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter界面跳转数据交互界面混合开发》 - Lucklyの博客 - 在阅读中遇见自己</title><meta name="Description" content="专注于IT互联网，包括但不限于Go语言(golang)、Flutter、Android、Python、项目管理、抖音分析、软件架构等"><meta property="og:title" content="《Flutter界面跳转数据交互界面混合开发》" />
<meta property="og:description" content="
本文主要介绍
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://luckly.work/posts/flutter/Flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" />
<meta property="article:published_time" content="2021-07-31T21:50:37+08:00" />
<meta property="article:modified_time" content="2021-07-31T21:50:37+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="《Flutter界面跳转数据交互界面混合开发》"/>
<meta name="twitter:description" content="
本文主要介绍
"/>
<meta name="application-name" content="Lucklyの博客 - 在阅读中遇见自己">
<meta name="apple-mobile-web-app-title" content="Lucklyの博客 - 在阅读中遇见自己"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://luckly.work/posts/flutter/Flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" /><link rel="prev" href="https://luckly.work/posts/flutter/Flutter%E6%B8%B2%E6%9F%93%E5%8E%9F%E7%90%86%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" /><link rel="next" href="https://luckly.work/posts/flutter/Flutter%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99%E6%95%B4%E7%90%863/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter界面跳转数据交互界面混合开发》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/luckly.work\/posts\/flutter\/Flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91\/"
        },"genre": "posts","keywords": "flutter","wordcount":  1989 ,
        "url": "https:\/\/luckly.work\/posts\/flutter\/Flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91\/","datePublished": "2021-07-31T21:50:37+08:00","dateModified": "2021-07-31T21:50:37+08:00","publisher": {
            "@type": "Organization",
            "name": "Breeze"},"author": {
                "@type": "Person",
                "name": "Breeze"
            },"description": ""
    }
    </script></head>
    <body header-desktop="" header-mobile=""><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : '' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">Lucklyの博客 - 在阅读中遇见自己</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/">首页</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/post/">归档</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/">分类</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/tags/">标签</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于我</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="https://github.com/ITmxs/">阅读清单</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">Contents</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter界面跳转数据交互界面混合开发》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>Breeze</a></span>&nbsp;<span class="post-category">included in <a href="/categories/Flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-31">2021-07-31</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;1989 words&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;4 minutes&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>Contents</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#界面跳转">界面跳转</a>
      <ul>
        <li><a href="#flutter界面内部跳转">Flutter界面内部跳转</a></li>
        <li><a href="#flutter界面与native界面跳转">Flutter界面与Native界面跳转</a></li>
      </ul>
    </li>
    <li><a href="#数据交互">数据交互</a>
      <ul>
        <li><a href="#flutter调用native">Flutter调用Native</a></li>
        <li><a href="#native调用flutter">Native调用Flutter</a></li>
      </ul>
    </li>
    <li><a href="#界面混合开发">界面混合开发</a>
      <ul>
        <li><a href="#native嵌套flutter">Native嵌套Flutter</a></li>
        <li><a href="#flutter嵌套native">Flutter嵌套Native</a></li>
      </ul>
    </li>
    <li><a href="#heading"></a></li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍</p>
</blockquote>
<h2 id="界面跳转">界面跳转</h2>
<p>Flutter界面跳转设计到两种类型：Flutter界面内部跳转、Flutter与Native界面之间跳转。</p>
<h3 id="flutter界面内部跳转">Flutter界面内部跳转</h3>
<h4 id="正常跳转">正常跳转</h4>
<p>Flutter内部维护一个界面堆栈，跳转时可以直接跳转：</p>
<pre><code>Navigator.push(context, new MaterialPageRoute(builder: (context) =&gt; new SecondPage()),);
</code></pre><p>也可以预先设置路由，通过路由名称进行跳转</p>
<pre><code>routes: {
    &quot;nameRoute&quot;:(BuildContext context)=&gt;new SecondPage(),
    &quot;thirdRoute&quot;:(BuildContext context)=&gt;new ThirdPage(title:&quot;请输入昵称&quot;),
  },
  
  ···
  Navigator.of(context).pushNamed(&quot;nameRoute&quot;);
</code></pre><p>界面返回：</p>
<p>在堆栈中弹出该界面</p>
<pre><code>Navigator.pop(context)
</code></pre><h4 id="带参跳转">带参跳转</h4>
<p>带参跳入很简单，只需要在需要跳转的Widget中增加参数就可以了。</p>
<p>带参跳出通过 <code>Navigator.pop(context, [ T result ])</code>中携带具体参数。
接收方需要指定返回结果，例如下面示例：</p>
<pre><code>Navigator.push&lt;String&gt;(context,
      new MaterialPageRoute(builder: (BuildContext context) {
    return new ThirdPage(title: &quot;请输入昵称&quot;);   /// 跳转到第三页，并且传递参数过去
    })).then((String result) {

    // 接收返回值的逻辑处理，通过一个 Dialog 展示出来
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new AlertDialog(
            content: new Text(&quot;您输入的昵称为:$result&quot;),
          );
        });
  });
</code></pre><h4 id="其它跳转方式">其它跳转方式</h4>
<ul>
<li>popAndPushNamed 退栈然后入栈一个指定name的页面</li>
<li>popUntil 重复调用pop直到predicate返回true</li>
<li>pushAndRemoveUntil 跳转，然后清栈</li>
</ul>
<h3 id="flutter界面与native界面跳转">Flutter界面与Native界面跳转</h3>
<h4 id="native界面跳转flutter界面">Native界面跳转Flutter界面</h4>
<p>最简单的方式，直接通过Native原生跳转，第二个Native中加载Flutter，不过这种方式不推荐。</p>
<p>实际上同样可以通过router指定具体的page(<strong>这部分存疑，只查到预览版使用该功能，正式版该功能未找到</strong>)，看如下代码：</p>
<pre><code>View flutterView = Flutter.createView(
  MainActivity.this,
  getLifecycle(),
  &quot;route1&quot;
);
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(600, 800);
layout.leftMargin = 100;
layout.topMargin = 200;
setContentView(flutterView);
</code></pre><p>该方法说明见 <a href="https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps#experiment-turn-the-flutter-project-into-a-module" target="_blank" rel="noopener noreffer">Add Flutter to existing apps</a></p>
<p>正式版中未找到相关文档说明，不过在官方代码中有如下示例：</p>
<pre><code>···

String[] args = getArgsFromIntent(getIntent());
        FlutterMain.ensureInitializationComplete(getApplicationContext(), args);
        
···

FlutterRunArguments runArguments = new FlutterRunArguments();
        runArguments.bundlePath = FlutterMain.findAppBundlePath(getApplicationContext());
        
···

flutterView = getFlutterView();
flutterView.runFromBundle(runArguments);

···

setContentView(flutterView);
</code></pre><p>可以通过参数指定flutter界面的具体信息，并进行展示。</p>
<h4 id="flutter界面跳转native界面">Flutter界面跳转Native界面</h4>
<p>Flutter跳Native界面利用的是<code>MethodChannel</code>，也就是下面数据交互部分的内容。Flutter发送一个信号通知到Native端，执行预设的工作。</p>
<p>例如：</p>
<pre><code>new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
  new MethodChannel.MethodCallHandler() {
      @Override
      public void onMethodCall(MethodCall call, MethodChannel.Result result) {
          //打开新的Activity
          startActivity(new Intent(MainActivity.this, FloatingActivity.class));
      }
  });
</code></pre><h2 id="数据交互">数据交互</h2>
<p>Flutter与Native的互相调用，必须通过Platform Channel来实现。</p>
<p>Flutter定义了三种不同的Channel，分别有不同的用途：</p>
<ul>
<li>BasicMessageChannel：用于传递字符串和半结构化的信息</li>
<li>MethodChannel：用于传递方法调用，常用于Flutter调用Native</li>
<li>EventChannel: 用于数据流通信，常用与Native通知Flutter</li>
</ul>
<p>这三种数据交互采用同样的方式，有三个相同的字段：String name、BinaryMessenger messenger、MethodCodec codec.</p>
<p>其中name唯一标识当前channel，messenger进行消息传递，codec用于二进制格式数据与基础数据之间的编解码。</p>
<p>另外还有Handler用于消息处理，存在三种Handler MessageHandler、MethodHandler、StreamHandler分别对应三种Channel</p>
<p>示例如下：</p>
<p>Flutter端</p>
<pre><code>static const EventChannel _eventChannel = const EventChannel('samples.flutter.io/charging');
static const MethodChannel _methodChannel = const MethodChannel('samples.flutter.io/battery');
</code></pre><p>Native端</p>
<pre><code>public static void registerWith(Registrar registrar) {
        /**
         * Channel名称：必须与Flutter App的Channel名称一致
         */
        private static final String METHOD_CHANNEL = &quot;samples.flutter.io/battery&quot;;
        private static final String EVENT_CHANNEL = &quot;samples.flutter.io/charging&quot;;

        final MethodChannel methodChannel = new MethodChannel(registrar.messenger(), METHOD_CHANNEL);
        
        final EventChannel eventChannel = new EventChannel(registrar.messenger(), EVENT_CHANNEL);
        eventChannel.setStreamHandler(plugin);
    }
</code></pre><p>首先在Flutter与Native注册Channel的name标识，进行绑定。</p>
<h3 id="flutter调用native">Flutter调用Native</h3>
<p>Flutter端</p>
<pre><code>Future&lt;String&gt; getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await _methodChannel.invokeMethod('getBatteryLevel',{'paramName':'paramVale'});
      batteryLevel = 'Battery level: $result%.';
    } catch(e) {
      batteryLevel = 'Failed to get battery level.';
    }
    return batteryLevel;
  }
</code></pre><p>Native端</p>
<pre><code>methodChannel.setMethodCallHandler(new MethodCallHandler(){

  @Override
    public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals(&quot;getBatteryLevel&quot;)) {
            Random random = new Random();
            result.success(random.nextInt(100));
        } else {
            result.notImplemented();
        }
    }
});
</code></pre><h3 id="native调用flutter">Native调用Flutter</h3>
<p>Flutter端</p>
<pre><code>void listenNativeEvent() {
  _eventChannel.receiveBroadcastStream().listen(_onEvent, onError:_onError);
}

void _onEvent(Object event) {
  print(&quot;Battery status: ${event == 'charging' ? '' : 'dis'}charging.&quot;);
}

void _onError(Object error) {
  print('Battery status: unknown.');
}
</code></pre><p>Native端</p>
<pre><code>eventChannel.setStreamHandler(new EventChannel.StreamHandler(){

  @Override
    public void onListen(Object obj, EventChannel.EventSink eventSink) {
        createChargingStateChangeReceiver(eventSink);
    }

    @Override
    public void onCancel(Object obj) {
    }
});

private BroadcastReceiver createChargingStateChangeReceiver(final EventSink events) {
    return new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

            if (status == BatteryManager.BATTERY_STATUS_UNKNOWN) {
                events.error(&quot;UNAVAILABLE&quot;, &quot;Charging status unavailable&quot;, null);
            } else {
                boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                        status == BatteryManager.BATTERY_STATUS_FULL;
                events.success(isCharging ? &quot;charging&quot; : &quot;discharging&quot;);
            }
        }
    };
}
</code></pre><h2 id="界面混合开发">界面混合开发</h2>
<p>混合开发同样分为两种:Native嵌套Flutter、Flutter嵌套Native</p>
<h3 id="native嵌套flutter">Native嵌套Flutter</h3>
<p>这部分很简单，直接将FlutterView作为一个简单的View操作就可以了，同样支持xml配置。如：</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
  ···
  super.onCreate(savedInstanceState);
    FlutterMain.ensureInitializationComplete(getApplicationContext(), args);
  setContentView(R.layout.flutter_view_layout);
  ···
  flutterView = findViewById(R.id.flutter_view);
  messageChannel = new BasicMessageChannel&lt;&gt;(flutterView, CHANNEL, StringCodec.INSTANCE);
  ···
}
</code></pre><h3 id="flutter嵌套native">Flutter嵌套Native</h3>
<p>这种方式也不复杂，在Flutter中支持AndroidView、UiKitView来分别支持Android、iOS原生控件展示。以Android为例：</p>
<p>首先在dart语言中设置AndroidView以及该控件的类型标识</p>
<pre><code>new Expanded(child: AndroidView(viewType: &quot;ACalendarView&quot;))
</code></pre><p>剩下的就全部在Native端进行配置</p>
<pre><code>// 注册类型标识
PluginRegistry.Registrar registrar = registry.registrarFor(key);
        registrar.platformViewRegistry().registerViewFactory(&quot;ACalendarView&quot;, new ACalendarViewFactory(new StandardMessageCodec(), calendarView));
</code></pre><p>指定需要展示的View</p>
<pre><code>public class ACalendarViewFactory extends PlatformViewFactory {

    private View calendarView;

    public ACalendarViewFactory(MessageCodec&lt;Object&gt; createArgsCodec, View calendarView) {
        super(createArgsCodec);
        this.calendarView = calendarView;
    }

    @Override
    public PlatformView create(Context context, int i, Object o) {
        return new PlatformView() {
            @Override
            public View getView() {
                return calendarView;
            }

            @Override
            public void dispose() {

            }
        };
    }
}
</code></pre><h2 id="heading"></h2></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>Updated on 2021-07-31</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">Back</a></span>&nbsp;|&nbsp;<span><a href="/">Home</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/flutter/Flutter%E6%B8%B2%E6%9F%93%E5%8E%9F%E7%90%86%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" class="prev" rel="prev" title="《Flutter渲染原理与性能优化》"><i class="fas fa-angle-left fa-fw"></i>《Flutter渲染原理与性能优化》</a>
            <a href="/posts/flutter/Flutter%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99%E6%95%B4%E7%90%863/" class="next" rel="next" title="《Flutter学习资料整理3》">《Flutter学习资料整理3》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">Powered by <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> | Theme - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">Breeze</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="Back to Top">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="View Comments">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript" src="/lib/sharer/sharer.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"Copy to clipboard","maxShownLines":10},"comment":{}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
